class Compiler {
  // 1、接收 vm 参数
  constructor (vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(vm.$el)
  }
  // 2、编译模板，处理文本节点和元素节点
  compile (el) {
    const childNodes = el.childNodes
    Array.from(el.childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        this.compileElement(node)
      }

      // 如果存在子元素，继续递归处理
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  // 5、编译元素节点，处理指令
  compileElement (node) {
    // 遍历所有指令节点
    Array.from(node.attributes).forEach(attr => {
      let attrName = attr.name 
      if (this.isDirective(attrName)){
        attrName = attrName.substr(2)
        let key = attr.value
        this.updater(node, key, attrName)
      }
    })
  }

  updater (node, key, attrName) {
    let arr = attrName.split(':')
    let updateFn = this[arr[0] + 'Updater']
    if (updateFn) {
      if (arr[1]) {

        updateFn.call(this, node, this.vm.$options.methods[key], key, arr[1])
      } else {
        updateFn.call(this, node, this.vm[key], key)
      }
    }
    // updateFn && updateFn.call(this, node, this.vm[key], key, arr[1])
  }

  textUpdater (node, value, key) {
    node.textContent = value
    // console.log('this', this)
    new Watcher(this.vm, key, newValue => {
      node.textContent = newValue
    })
  }

  modelUpdater (node, value, key) {
    node.value = value
    new Watcher(this.vm, key, newValue => {
      node.value = newValue
    })

    //视图改变触发
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }

  htmlUpdater (node, value, key) {
    node.innerHTML = value
    node.outerHTML = node.outerHTML.replace(/v-html(.+?)\s/, "")
    new Watcher(this.vm, key, newValue => {
      node.innerHTML = newValue
    })
  }

  onUpdater (node, value, key, eventName) {
    node.addEventListener(eventName, (e) => {
      console.log(e)
      value()
    })
  }

  // 6、编译文本节点，处理差值表达式
  compileText (node) {
    // console.dir(node)
    let reg = /\{\{(.+?)\}\}/
    const value = node.textContent
    if (reg.test(value)) {
      const key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])
      //响应式更新
      new Watcher(this.vm, key, newValue => {
        node.textContent = newValue
      })
    }
  }
  // 7、判断元素属性是否是指令
  isDirective (attrName) {
    return attrName.startsWith('v-')
  }
  // 3、判断文本节点
  isTextNode (node) {
    return node.nodeType === 3
  }
  // 4、判断元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
}
